import React, { Component } from 'react'
import './index.css';

export default class App extends Component {

    state = {
        left: 0
    }

    componentDidMount(){
        let step = 1;
        //启动定时器
        this.timer = setInterval(() => {
            //判断边界
            let maxLeft = this.out.offsetWidth - this.inner.offsetWidth;
            if(this.state.left >= maxLeft || this.state.left < 0){
                //逆向
                step *= -1;
            }
            // 修改 left 的值
            this.setState({
                left: this.state.left + step
            })
        }, 20);
    }

    componentWillUnmount(){
        //清除定时器
        clearInterval(this.timer);
    }

    render(){
        return <div ref={el => this.out = el} className="out">
            <div ref={el => this.inner = el} className="inner" style={{left: this.state.left + 'px'}}></div>
        </div>
    }
}
